package com.exm.sql.resolver;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.exm.sql.annotation.RequestField;
import jakarta.servlet.http.HttpServletRequest;
import netscape.javascript.JSObject;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
import jakarta.servlet.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.WebUtils;

@Component
public class RequestFieldArgumentResolver implements HandlerMethodArgumentResolver {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(RequestField.class) != null;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, 
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        RequestField annotation = parameter.getParameterAnnotation(RequestField.class);
        String fieldName = annotation.value();  // 获取字段名

        // 获取请求体
        HttpServletRequest request = ((ServletWebRequest) webRequest).getRequest();
        String body = getRequestBody(request);

        // 将请求体转换为对象
        JSONObject jsonObject =JSON.parseObject(body);
        if (jsonObject==null){
            return null;
        }
        Object value = jsonObject.get(fieldName);
        // 获取请求体中的字段值
        return value;
    }

    private String getRequestBody(HttpServletRequest request) throws IOException {
        // 如果没有被包装，则手动读取请求体
        StringBuilder body = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            body.append(line);
        }

        if (body.toString().equals("")){
            body.append( request.getAttribute("cachedRequestBody"));
        }
        // 将请求体缓存到请求属性中，方便后续访问
        request.setAttribute("cachedRequestBody", body.toString());

        return body.toString();
    }
}
